
(async ()=>{
    const fs=require('fs')
    const puppeteer = require('puppeteer');
    const {Get_apply_nos,verification_code,front_log,after_update}=require('./api')
    const {close_fn,handle,addCookies}=require('./tools')
    let msg='',page=null,browser=null,apply_nos=null
    try{
        apply_nos=await Get_apply_nos()
    }catch(err){
        console.log('服务器连接失败');
        
    }

	apply_nos=apply_nos.data.apply_nos
    
	if(!apply_nos.length){
		msg='暂无同步数据'
		front_log({ msg})
        close_fn(msg)
        return
    }else  
        console.log('已获取到待同步的申请号',apply_nos);

    try{
        browser =await puppeteer.launch({ 
            headless: false,
            devtools: false,
            defaultViewport:{
                width:1920,
                height:1080
            },
            ignoreDefaultArgs: ["--enable-automation"],
            args: ['--no-sandbox', '--disable-setuid-sandbox']
        })
        page = await browser.newPage();
        await addCookies( fs.readFileSync('./cookie.txt').toString() ,page,'cpquery.cnipa.gov.cn')
    }catch(err){
        console.log(err,'初始化出错，重试');
    }

    await page.goto('http://cpquery.cnipa.gov.cn/txnPantentInfoList.do?inner-flag:open-type=window&inner-flag:flowno='+new Date().getTime(),{  waitUntil:'networkidle0'})
   
    
    
    
    const login=async ()=>{
        // 18605119282  Pipi**13579
        // 17130723545  18012804778 Aa1381515!
        //17505119527 Ju..13579  13775540318 Heh6456776~
        await page.goto('http://cpquery.cnipa.gov.cn')
        await page.type('#username1', '17130723545')
        await page.type('#password1', 'Aa1381515!')
        await page.waitFor(500)
        await page.hover('#div2')
        await page.waitFor(1500)
        const X=1040,Y=229
        const base64=await page.screenshot({
            encoding:'base64',
            clip:{
                x:X,
                y:Y,
                width:305,
                height:248
            }
        })
        let res= await verification_code({
            user: 'St1nger',
            pass: 'IVERSON3399',
            softid:'901671', 
            codetype: '9103',  
            file_base64: base64
        })
        if(!res.err_no){
            let arr=res.pic_str.split('|')
            arr.forEach(async el=>{
                let pos=el.split(',')
                await page.mouse.click(+pos[0]+X,+pos[1]+Y)
            })
            
        }else{
            throw '验证码获取错误'
        }
        await page.waitFor(600)
        if(await page.$eval('#selectyzm_text',el => el.innerHTML)==='验证成功'){
            await page.click('#publiclogin')
            await page.waitForNavigation()
        }else{
            await login()
        }
    }

    
    
    if(!await page.$('#attention_token')){
        await login()
        if(!await page.$('#attention_token')){
            msg='登陆出错'
            front_log({ msg})
            close_fn(msg)
        }
        fs.writeFileSync('./cookie.txt',await page.evaluateHandle(() => document.cookie))
    }
    const func=function(arr){
        return Promise.all(arr.map(async el=>handle(el,browser)))
        .then(res=>{
            let err_arr=[],succ_arr=[]
            res.forEach((el,index)=>{
                let no=arr[index]
                if( !el || typeof(el)=='string' || el.code!=0 ){
                    err_arr.push(no)
                }else{
                    succ_arr.push(no)
                    after_update({apply_no:no})
                }
                
            })
            if(succ_arr.length)
                front_log({msg:`已成功同步：${succ_arr.length}条`+succ_arr.join(',')})
            if(err_arr.length)
                front_log({msg:`已失败同步：${err_arr.length}条`+err_arr.join(',')})
        })
        .catch(err=>{
            // browser.close('内部错误'+msg)
            msg='内部错误'+JSON.stringify(err)
            front_log({ msg})
            close_fn(msg)
        })
    }

    const loop_func=async function(){
        await func(JSON.parse(JSON.stringify(apply_nos)))
        const tmp=await Get_apply_nos()
        apply_nos=tmp.data.apply_nos 
        console.log('再次获取待同步数据：',apply_nos);
        
        if(!apply_nos.length){
            close_fn('已执行完毕')
            return
        }
        loop_func()
    }
    
    loop_func()



    
    

    
    
    

  
    
})()